// shopMallPackage/pages/shopCarList/shopCarList.js
import { queryCartList, addCartNumRequest, delCartRequest } from "../../../service/onetoone_service"
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    cartList: [],
    isAll: false,
    totalMoney: 0,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },



  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.queryCartList();
  },
  cancelQueryList() {
    queryCartList().then(res => {
      wx.hideLoading();
      console.log("JJLog:购物车列表是:" + JSON.stringify(res));
      if (res.code == 200) {
        let arr = res.data || [];
        if (arr && arr.length > 0) {
          arr.forEach((item, index) => {
            item.isChoose = this.data.cartList[index].isChoose
          })
          this.setData({
            cartList: [],
          })
          this.setData({
            cartList: arr
          })
        }
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || '查询失败',
        icon: "none"
      })
      console.log("JJLog:queryCartList", err);
    })
  },
  queryCartList() {
    wx.showLoading();
    queryCartList().then(res => {
      wx.hideLoading();
      console.log("JJLog:购物车列表是:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          cartList: res.data || []
        })
        if (this.data.cartList && this.data.cartList.length > 0) {
          let arr = this.data.cartList;
          arr.forEach((item) => {
            item.isChoose = false;
          })
          this.setData({
            cartList: arr,
          })
        }
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || '查询失败',
        icon: "none"
      })
      console.log("JJLog:queryCartList", err);
    })
  },

  // 全选操作:
  allSelectAction() {
    //已经全选
    if (this.data.isAll) {
      let arr = this.data.cartList;
      arr.forEach((item) => {
        item.isChoose = false
      })
      this.setData({
        cartList: arr,
        isAll: false,
        totalMoney: 0,
      })
    } else {
      // 未全选:
      let money = 0;
      let arr = this.data.cartList;
      arr.forEach((item) => {
        item.isChoose = true;
        money = money + (item.price * 100 * item.cartNum) / 100
      })
      this.setData({
        cartList: arr,
        isAll: true,
        totalMoney: money,
      })
    }
  },
  // 单个选中：
  singleSelectAction(e) {
    let totalMoney = this.data.totalMoney;
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    let isChoose = !item.isChoose
    //动态数组:
    let changeItem = 'cartList[' + index + '].isChoose';
    this.setData({
      [changeItem]: isChoose,
    })
    // true 加
    if (isChoose) {
      totalMoney = totalMoney + (item.price * 100 * item.cartNum) / 100
    } else {
      // 减
      totalMoney = (totalMoney * 100 - (item.price * item.cartNum) * 100) / 100
    }
    this.setData({
      totalMoney: totalMoney
    })

    // 是否全选:
    this.isAllAction();
  },
  isAllAction() {
    let arr = this.data.cartList;
    let selectNum = 0;
    arr.forEach((item) => {
      if (item.isChoose) {
        selectNum = selectNum + 1;
      }
    })
    if (selectNum == this.data.cartList.length) {
      this.setData({
        isAll: true
      })
    } else {
      this.setData({
        isAll: false
      })
    }
  },


  // 数量加减变化：
  onChangePrice(e) {
    let totalMoney = this.data.totalMoney;
    let index = e.currentTarget.dataset.index;
    let item = e.currentTarget.dataset.item;
    let originNum = item.cartNum;
    let num = e.detail;
    addCartNumRequest(item.id, num).then(res => {
      console.log("JJLog:操作成功:" + JSON.stringify(res));
      if (res.code == 200) {
        //动态数组:
        let changeItem = 'cartList[' + index + '].cartNum';
        this.setData({
          [changeItem]: num,
        })
        // 已经选中才影响总价
        if (item.isChoose) {
          if (originNum < num) {
            // 加:
            totalMoney = totalMoney + item.price;
          } else {
            // 减:
            totalMoney = (totalMoney * 100 - item.price * 100) / 100;
          }
          this.setData({
            totalMoney: totalMoney
          })

        }
      }
    }).catch(err => {
      wx.showToast({
        title: err || "操作失败",
        icon: "none"
      })
      let changeItem = 'cartList[' + index + '].cartNum';
      this.setData({
        [changeItem]: num - 1,
      })
      console.error("JJLog:addCartNumRequest:", err);
    })

  },

  // 删除一个购物车:
  cancelOneCon(e) {
    let totalMoney = this.data.totalMoney;
    let index = e.currentTarget.dataset.index;
    let arr = this.data.cartList;
    let item = e.currentTarget.dataset.item;
    let originNum = item.cartNum;
    wx.showLoading({
      title: '删除中...',
    })
    delCartRequest(item.id).then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        if (item.isChoose) {
          totalMoney = (totalMoney * 100 - item.price * 100 * originNum) / 100;
          this.setData({
            totalMoney: totalMoney,
          })
        }
        arr.splice(index, 1);
        this.setData({
          cartList: arr,
        })
        this.cancelQueryList();
        this.isAllAction();
      }

    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || '删除失败',
        icon: "none"
      })
      console.error("JJLog:cancelOneCon", err);
    })
  },
  // 去结算
  goToSettleAction() {
    if (this.data.totalMoney < 0 || this.data.totalMoney == 0) {
      wx.showToast({
        title: '请选择要结算的商品',
        icon: "none"
      })
      return;
    }
    let arr = this.data.cartList;
    let sArr = [];
    arr.forEach((item) => {
      if (item.isChoose) {
        sArr.push(item)
      }
    })
    app.globalData.cartList = sArr;
    app.globalData.cartMoney = this.data.totalMoney;
    console.log("JJLog:要结算的是:" + JSON.stringify(app.globalData.cartList));
    wx.navigateTo({
      url: '/shopMallPackage/pages/carSettle/carSettle',
    })
  },
})